package com.hitqz.robot.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.hitqz.robot.api.business.enums.RobotModelEnum;
import com.hitqz.robot.api.business.enums.TicketsFormFieldEnum;
import com.hitqz.robot.api.business.enums.TicketsStatusEnum;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolTicketsDto;
import com.hitqz.robot.api.common.dto.warning.AddWarningDto;
import com.hitqz.robot.api.common.entity.*;
import com.hitqz.robot.api.dispatch.protocol.dto.FormConfigModalDto;
import com.hitqz.robot.api.dispatch.protocol.dto.FormFieldConfigModalDto;
import com.hitqz.robot.biz.mapper.TicketsTaskMapper;
import com.hitqz.robot.biz.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author xupkun
 * @date 2024/6/3
 */
@Service
@AllArgsConstructor
@Slf4j
public class TicketsTaskServiceIml extends ServiceImpl<TicketsTaskMapper, TicketsTask> implements TicketsTaskService {

    private final PatrolItemService patrolItemService;

    private final PatrolPosPoseGroupService patrolPosPoseGroupService;

    private final RobotService robotService;

    private final TicketsFlowMatchService ticketsFlowMatchService;

    @Override
    public boolean createTicket(String content, Tickets tickets) {
        List<TicketsTask> tasks = Lists.newArrayList();
        if (StrUtil.isBlank(content)){
            log.warn("工单内容为空,不创建工单任务");
            AddWarningDto addWarningDto = new AddWarningDto();
            addWarningDto.setCode("0");
            addWarningDto.setTitle("任务生成错误");
            addWarningDto.setContent("无任务内容");
            addWarningDto.setSuggestion("请检查任务数据是否正确");
            addWarningDto.setLevel(1);
            SpringUtil.getApplicationContext().publishEvent(addWarningDto);
            return false;
        }
        FormConfigModalDto dto = JSONObject.parseObject(content, FormConfigModalDto.class);
        String fromName = dto.getFormName();
        Robot robot = robotService.getDefaultRobot();
        if (fromName.contains(robot.getRobotModel().toLowerCase())) {
            List<FormFieldConfigModalDto> fields = dto.getFields();
            Map<String, Object> taskFields = Maps.newHashMap();
            for (FormFieldConfigModalDto field : fields) {
                String currentValue = field.getCurrentValue();
                String name = field.getName();
                log.info("任务内容为{}:{} ", name, currentValue);
                taskFields.put(name, currentValue);
            }
            if (robot.getRobotModel().equals(RobotModelEnum.PATROL.getFlag())) {
                //巡检
                this.createPatrolTask(taskFields, tickets, tasks);
            }else {
                //通用
                // 生成tickets_task 设置默认流程为 pre_business do_business end_business
                //前置
                TicketsTask preTask = new TicketsTask();
                preTask.setTicketsId(tickets.getId());
                preTask.setCreateTime(new Date());
                preTask.setStatus(TicketsStatusEnum.TICKETS_TASK_NONE.getCode());
                preTask.setContent("检测准备动作");
                preTask.setFlowName("pre_business");
                FlowPatrolPreAndEndTicketsDto preDto = new FlowPatrolPreAndEndTicketsDto();
                preDto.setModalData(taskFields);
                preTask.setParseOrderParams(JSONObject.toJSONString(preDto));
                tasks.add(preTask);
                // 任务
                // 具体任务具体解析
                // 巡检类型的任务
                if (fields.contains("patrolItemIds")) {
                    // 巡检任务
                    String patrolItemIds = (String) taskFields.get("patrolItemIds");
                    String[] items = patrolItemIds.split(",");
                    for (String itemId : items) {
                        //巡检内容
                        TicketsTask taskContent = BeanUtil.copyProperties(preTask, TicketsTask.class);
                        taskContent.setContent("检测项" + itemId);
                        taskContent.setFlowName("patrol_content");
                        FlowPatrolTicketsDto patrolTicketsDto = new FlowPatrolTicketsDto();
                        PatrolItem item = patrolItemService.getById(itemId);
                        PatrolPosPoseGroup posPoseGroup = patrolPosPoseGroupService.getById(item.getPatrolPosPoseGroupId());
                        patrolTicketsDto.setPosId(posPoseGroup.getPosId());
                        patrolTicketsDto.setPoseGroupId(posPoseGroup.getPatrolPoseGroupId());
                        patrolTicketsDto.setPatrolItemId(item.getId().intValue());
                        patrolTicketsDto.setDetectEquipmentId(item.getEquipmentId());
                        taskContent.setParseOrderParams(JSONObject.toJSONString(patrolTicketsDto));
                        tasks.add(taskContent);
                    }
                } else {
                    // 其他类型
                    TicketsTask taskContent = BeanUtil.copyProperties(preTask, TicketsTask.class);
                    taskContent.setContent("");
                    // 匹配业务场景流程
                    String flowName = "do_business";
                    List<TicketsFlowMatch> ticketsFlowMatches = ticketsFlowMatchService.list();

                    Optional<TicketsFlowMatch> ticketsFlowMatch = ticketsFlowMatches.stream().filter(
                            item -> tickets.getName().contains(item.getKeyWorld())).findFirst();

                    if (ticketsFlowMatch.isPresent()) {
                        flowName = ticketsFlowMatch.get().getFlowName();
                    }
                    taskContent.setFlowName(flowName);
                    taskContent.setParseOrderParams(JSONObject.toJSONString(preDto));
                    tasks.add(taskContent);
                }
                // 后置
                TicketsTask endTask = BeanUtil.copyProperties(preTask, TicketsTask.class);
                endTask.setContent("检测结束动作");
                endTask.setFlowName("end_business");
                FlowPatrolPreAndEndTicketsDto endDto = new FlowPatrolPreAndEndTicketsDto();
                endDto.setModalData(taskFields);
                endTask.setParseOrderParams(JSONObject.toJSONString(preDto));
                tasks.add(endTask);
            }
            // 保存
            this.saveBatch(tasks);
            log.info("保存tasks");
            return true;
        } else {
            AddWarningDto addWarningDto = new AddWarningDto();
            addWarningDto.setCode("0");
            addWarningDto.setTitle("任务生成错误");
            addWarningDto.setContent("未知的任务类型数据" + fromName);
            addWarningDto.setSuggestion("请检查任务数据是否正确");
            addWarningDto.setLevel(1);
            SpringUtil.getApplicationContext().publishEvent(addWarningDto);
        }
        return false;
    }


    private void createPatrolTask(Map<String, Object> taskFields, Tickets tickets, List<TicketsTask> tasks) {
        String patrolItemIds =(String) taskFields.get(TicketsFormFieldEnum.PATROL_ITEM_IDS.getFieldName());
        String[] items = patrolItemIds.split(",");
        TicketsTask preTask = new TicketsTask();
        preTask.setTicketsId(tickets.getId());
        preTask.setCreateTime(new Date());
        preTask.setStatus(TicketsStatusEnum.TICKETS_TASK_NONE.getCode());
        preTask.setContent("检测准备动作");
        preTask.setFlowName("patrol_pre");
        FlowPatrolPreAndEndTicketsDto preDto = new FlowPatrolPreAndEndTicketsDto();
        preDto.setPatrolItemIds(patrolItemIds);
        preTask.setParseOrderParams(JSONObject.toJSONString(preDto));
        tasks.add(preTask);
        for (String itemId : items) {
            //巡检内容
            TicketsTask taskContent = BeanUtil.copyProperties(preTask,TicketsTask.class);
            taskContent.setContent("检测项"+itemId);
            taskContent.setFlowName("patrol_content");
            FlowPatrolTicketsDto patrolTicketsDto = new FlowPatrolTicketsDto();
            PatrolItem item = patrolItemService.getById(itemId);
            PatrolPosPoseGroup PosPoseGroup = patrolPosPoseGroupService.getById(item.getPatrolPosPoseGroupId());
            patrolTicketsDto.setPosId(PosPoseGroup.getPosId());
            patrolTicketsDto.setPoseGroupId(PosPoseGroup.getPatrolPoseGroupId());
            patrolTicketsDto.setPatrolItemId(item.getId().intValue());
            patrolTicketsDto.setDetectEquipmentId(item.getEquipmentId());
            taskContent.setParseOrderParams(JSONObject.toJSONString(patrolTicketsDto));
            tasks.add(taskContent);
        }
        //巡检结束动作
        TicketsTask endTask = BeanUtil.copyProperties(preTask,TicketsTask.class);
        endTask.setContent("检测结束动作");
        endTask.setFlowName("patrol_end");
        FlowPatrolPreAndEndTicketsDto endDto = new FlowPatrolPreAndEndTicketsDto();
        String patrolEndPosId =(String) taskFields.get(TicketsFormFieldEnum.PATROL_END_POS_ID.getFieldName());
        endDto.setEndPosId(Integer.parseInt(patrolEndPosId));
        endTask.setParseOrderParams(JSONObject.toJSONString(endDto));
        tasks.add(endTask);
    }

}
